import { animationsClass, download } from './index'
import axios from 'axios'
import JSZip from 'jszip'

const CODE_TEMPLATE_H5 = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>#{pageTitle}#</title><script src="https://unpkg.com/axios/dist/axios.min.js"></script><link rel="stylesheet" href="./lib/animate.css"><style>* {padding: 0;margin: 0;}html,body {width: 100vw;height: 100vh;}</style></head><body>#{containerInnerHTML}#</body></html>`

// 导出h5代码
export default function exportH5(panelJson) {
  let targetCodeTemplate = CODE_TEMPLATE_H5.replace('#{pageTitle}#', panelJson.container.title)
  panelJson.comps = panelJson.comps.filter(item => item.config.visible)
  const panelCode = createHtmlStr(genContainerNode(panelJson))
  targetCodeTemplate = targetCodeTemplate.replace('#{containerInnerHTML}#', panelCode)
  const htmlBolb = new Blob([targetCodeTemplate], { type: 'text/html' })
  axios({
    url: '/download/animate.css',
    method: 'get',
    responseType: 'text'
  }).then(({ data }) => {
    const zip = new JSZip()
    const rootFolder = zip.folder(panelJson.container.title)
    rootFolder.folder('lib').file('animate.css', new Blob([data], { type: 'text/css' }))
    rootFolder.file('index.html', htmlBolb)
    zip.generateAsync({ type: 'blob', compression: 'DEFLATE' }).then(content => {
      download(content, `${panelJson.container.title}.zip`)
    })
  })
}

// 创建html字符串
function createHtmlStr(node) {
  const div = document.createElement('div')
  div.appendChild(node)
  return div.innerHTML
}

// 容器跟节点
function genContainerNode({ id, container, comps }) {
  const containerEl = document.createElement('div')
  containerEl.setAttribute('id', id)
  const styles = ['position: relative']
  styles.push(`width: ${container.width}%; height: ${container.height}%;`)
  if(container.backgroundColor) {
    styles.push(`background-color: ${container.backgroundColor}`)
  }
  if(container.backgroundImage) {
    styles.push(`background-image: url(${container.backgroundColor})`)
  }
  styles.push(`background-size: ${container.backgroundSize}`)
  containerEl.setAttribute('style', styles.join(';'))
  for(let comp of comps) {
    const compNode = genCompNode(comp)
    if(compNode) {
      containerEl.appendChild(compNode)
    }
  }
  return containerEl
}

// 组件节点
function genCompNode(comp, data) {
  switch (comp.compKey) {
    case 'seniorContainer':
      return genChildContainerNode(comp, data)
    case 'seniorLoop':
      return genChildLoopNode(comp, data)
    case 'basicText':
      return genTextNode(comp, data)
    case 'basicImage':
      return genImageNode(comp, data)
    default:
      return null
  }
}

// 组件容器节点
function genChildContainerNode(comp) {
  const childContainerEl = document.createElement('div')
  const styles = getCompStyles(comp, childContainerEl)
  childContainerEl.setAttribute('style', styles.join('; '))
  const temp = document.createElement('div')
  temp.setAttribute('style', 'width: 100%; height: 100%; position: relative;')
  for(let child of comp.children) {
    const childNode = genCompNode(child)
    if(childNode) {
      temp.appendChild(childNode)
    }
  }
  childContainerEl.appendChild(temp)
  return childContainerEl
}

// 循环组件节点
function genChildLoopNode(comp) {
  const loopEl = document.createElement('div')
  const styles = getCompStyles(comp, loopEl)
  loopEl.setAttribute('style', styles.join('; '))
  const temp = document.createElement('div')
  const attrs = getAttrs(comp.attrs)
  temp.setAttribute(
    'style',
    `width: 100%; 
    height: 100%; 
    padding-top: ${attrs.paddingTop}px; 
    padding-bottom: ${attrs.paddingBottom}px; 
    padding-left: ${attrs.paddingLeft}px; 
    padding-right: ${attrs.paddingRight}px; 
    display: ${attrs.display};
    flex-direction: ${attrs.flexDirection};
    justify-content: ${attrs.justifyContent};
    align-items: ${attrs.alignItems};
    flex-wrap: ${attrs.flexWrap};
    align-content: ${attrs.alignContent};`
  )
  for(let item of comp.data) {
    const childNode = genCompNode(comp.children[0], item)
    childNode.style.position = 'static'
    if(childNode) {
      temp.appendChild(childNode)
    }
  }
  loopEl.appendChild(temp)
  return loopEl
}

// 文本节点
function genTextNode(comp, data) {
  const textEl = document.createElement('div')
  const textContainerEl = document.createElement('div')
  const styles = getCompStyles(comp, textEl)
  styles.push('width: 100%', 'height: 100%', 'display: flex', 'align-items: center', 'justify-content: center')
  const { color, fontWeight, fontStyle, textDecoration, fontSize } = getAttrs(comp.attrs)
  styles.push(`color: ${color}`)
  styles.push(`font-weight: ${fontWeight}`)
  styles.push(`font-style: ${fontStyle}`)
  styles.push(`text-decoration: ${textDecoration}`)
  styles.push(`font-size: ${fontSize}px`)
  textContainerEl.setAttribute('style', styles.join('; '))
  textContainerEl.textContent = data ? data.data : comp.data.data
  textEl.appendChild(textContainerEl)
  return textEl
}

// 图片节点
function genImageNode(comp, data) {
  const imageEl = document.createElement('div')
  const styles = getCompStyles(comp, imageEl)
  imageEl.setAttribute('style', styles.join('; '))
  const img = document.createElement('img')
  img.setAttribute('src', data ? data.data : comp.data.data)
  img.setAttribute('style', `width: 100%; height: 100%; object-fit: cover;`)
  imageEl.appendChild(img)
  return imageEl
}

// 统一属性设置
function getCompStyles(comp, el) {
  el.setAttribute('id', comp.id)
  const styles = ['position: absolute', `z-index: ${comp.style.zIndex}`]
  for(let k in comp.resizeGrid) {
    styles.push(`${k}: ${comp.resizeGrid[k]}`)
  }
  if(comp.style.backgroundColor) {
    styles.push(`background-color: ${comp.style.backgroundColor}`)
  }
  if(comp.style.backgroundImage) {
    styles.push(`background-image: url(${comp.style.backgroundImage})`)
  }
  if(comp.style.border.show) {
    styles.push(`border: ${comp.style.border.borderWidth}px ${comp.style.border.borderType} ${comp.style.border.borderColor}`)
    styles.push(`border-radius: ${comp.style.border.borderRadius}px`)
  }
  if(comp.style.animate.classNames && comp.style.animate.classNames.length) {
    if(comp.style.animate.isInfinite) {
      el.setAttribute('class', animationsClass(comp.style.animate.classNames) + ' animate__infinite')
    } else {
      el.setAttribute('class', animationsClass(comp.style.animate.classNames))
    }
  }
  return styles
}

function getAttrs(attrList) {
  const attrs = {}
  if(attrList && attrList.length) {
    for(let attr of attrList) {
      attrs[attr.name] = attr.value
    }
  }
  return attrs
}